package fr.nekloth.android.hinode;

/* NEWS ***************************************************

 */

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.TimeZone;

import org.acra.ErrorReporter;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.AlertDialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.graphics.Typeface;

import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.net.Uri;
import android.os.Bundle;

import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;

import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;

import uk.me.jstott.sun.*;
import uk.me.jstott.coordconv.*;
import uk.me.jstott.util.*;


public class applicationStartup extends Activity  {
	
    public static boolean debugMode = false;

    // Variables
    //Donate URL
  	String applicationURL = "http://code.google.com/p/helios-application";
    
  	public static final String GLOBAL_FONT_TO_USE = "fonts/augie.ttf";
  	
  	/* Variables IMAGES */
  	int ICON_main_coordinates    = R.drawable.coordinates;
  	int ICON_main_sunrise        = R.drawable.sunrise;
  	int ICON_main_sunset         = R.drawable.sunset;
  	int ICON_main_alarm_active   = R.drawable.isactive;
  	int ICON_main_alarm_inactive = R.drawable.isinactive;
  	
	/*Variables int�ressantes */
	public static LatitudeLongitude currentPosition = new LatitudeLongitude(48.85327d, 2.34852d);

	public static TimeZone currentTimeZone = TimeZone.getDefault();
    public static Calendar currentCalendar = Calendar.getInstance();
    public static double julianCalendar = JulianDateConverter.dateToJulian(currentCalendar);
    static Date today = new Date();
    public static boolean daylightSavingTime = currentTimeZone.inDaylightTime(today);
    
    public static Time[] referenceHours = {new Time(0,0,0d),new Time(0,0,0d),new Time(0,0,0d),new Time(0,0,0d)} ;

    public static boolean applicationPOSITIONset;

    public static boolean sunriseVStwilight = true; // true=morning / false=twilight
    public static boolean sunsetVStwilight = true; // true=evening / false=twilight
    
    public static SunAlarm sAlarm1 = new SunAlarm();
    public static SunAlarm sAlarm2 = new SunAlarm();
 
	public static int MAIN_CHOICE_COORDINATES = 0;
	public static int MAIN_CHOICE_MORNING_TIME = 1;
	public static int MAIN_CHOICE_EVENING_TIME = 2;
	public static int MAIN_CHOICE_ALARM_1 = 3;
	public static int MAIN_CHOICE_ALARM_2 = 4;
	public static int MAIN_CHOICE_NOTIFICATION = 5;

	public static boolean applicationAlreadyLoaded;
    
    public static final int SUB_ACTIVITY_REQUEST_CODE = 240708; 
    
    public static final String MYPREFS = "hinode_application_settings";
    
    public static int ALARM_ID_1 = 240727061, ALARM_ID_2=240727062;
    private NotificationManager mNotificationManager;
    
    public int MY_APP_NOTIFICATION_ID = 24072706;

    static final int MAPS_ZOOM_LEVEL = 10;
    
    // For the MENU
	static final int MENU_ABOUT_ID = 99;
	static final int MENU_QUICK_HELP = 97;
	
	//For VOLUME 
	static final int MENU_VOLUME_SILENCE = 4;
	static final int MENU_VOLUME_LOW = 5;
	static final int MENU_VOLUME_MEDIUM = 6 ;
	static final int MENU_VOLUME_HIGH = 7;

	static final int MENU_TONE_POP  = R.raw.pop;
	

	int initialStreamVolume = 0;
	int initialSystemStreamVolume = 0;
	int selectedVolumeLevel = MENU_VOLUME_MEDIUM;
	int selectedTone        = MENU_TONE_POP;

	int warpZoneCounter = 0;
	static final int WARP_ZONE_LIMIT = 3;
	
	public boolean doubleAlarmWarningAlreadyShown = false;
	
	Context theContext;
    
	public void crashDebugAdditionalInformation() {
		ErrorReporter.getInstance().addCustomData("Version", (String)getText(R.string.app_version));
		ErrorReporter.getInstance().addCustomData("Language", (String)getText(R.string.app_language_name));
		ErrorReporter.getInstance().addCustomData("AppStartup.GPSLocation", applicationStartup.currentPosition.toSimplifyString());
		ErrorReporter.getInstance().addCustomData("AppStartup.Time Zone", applicationStartup.currentTimeZone.getDisplayName() + "(" + applicationStartup.currentTimeZone.getID() + ")");
		ErrorReporter.getInstance().addCustomData("AppStartup.Daylight saving", ""+daylightSavingTime);
		ErrorReporter.getInstance().addCustomData("AppStartup.Ref Hour MORNING TWILIGHT",referenceHours[SunAlarm.REFERENCE_MORNING_TWILIGHT].toSimplifiedString());
		ErrorReporter.getInstance().addCustomData("AppStartup.Ref Hour SUNRISE",referenceHours[SunAlarm.REFERENCE_SUNRISE].toSimplifiedString());
		ErrorReporter.getInstance().addCustomData("AppStartup.Ref Hour SUN SET",referenceHours[SunAlarm.REFERENCE_SUNSET].toSimplifiedString());
		ErrorReporter.getInstance().addCustomData("AppStartup.Ref Hour EVENING TWILIGHT",referenceHours[SunAlarm.REFERENCE_EVENING_TWILIGHT].toSimplifiedString());
	}
	
	
    /* **************************************************************
     * Functions for TOASTS
     **************************************************************** */
    protected void toastLongInfo(String theMessage) {
    	Toast.makeText(this, theMessage,Toast.LENGTH_LONG).show();
    }

    protected void toastShortInfo(String theMessage) {
    	Toast.makeText(this, theMessage,Toast.LENGTH_SHORT).show();
    }

    public static void toastInfo(Context theContext,String theMessage) {
    	Toast.makeText(theContext, theMessage,Toast.LENGTH_LONG).show();
    }

    

    /* **************************************************************
     * Functions to build alarm text
     **************************************************************** */
    protected String buildAlarmTitle(SunAlarm sa) {
    	String myResult = new String("");
    	Resources mesRessources = this.getResources();
    	myResult += mesRessources.getText(R.string.t_alarm);
    	myResult += " " + mesRessources.getText(R.string.at) + " " + sa.getAlarmTime().toSimplifiedString();
    	myResult += " - ";
    	myResult += (sa.isActive())?mesRessources.getText(R.string.active):mesRessources.getText(R.string.inactive);    	
    	return myResult;
    }
    
    protected String buildAlarmContent(SunAlarm sa) {
    	String myResult = new String(""), txttmp = new String("");
    	Resources mesRessources = this.getResources();
		myResult += ((sa.getAlarmHour()<10)?"0"+sa.getAlarmHour():sa.getAlarmHour()) + ":";
		myResult += ((sa.getAlarmMinute()<10)?"0"+sa.getAlarmMinute():sa.getAlarmMinute());
		
		if (sa.getRelative()) {
			txttmp = (String) mesRessources.getText(R.string.before);
		} else {
			txttmp = (String) mesRessources.getText(R.string.after);
		}
		
		myResult += " " + txttmp + " ";
		
		int temp = sa.getMomentReference();
		
		if (temp == SunAlarm.REFERENCE_EVENING_TWILIGHT) {txttmp = (String) mesRessources.getText(R.string.evening_twilight_time_min);}
		if (temp == SunAlarm.REFERENCE_MORNING_TWILIGHT) {txttmp = (String) mesRessources.getText(R.string.morning_twilight_time_min);}
		if (temp == SunAlarm.REFERENCE_SUNRISE) {txttmp = (String) mesRessources.getText(R.string.sunrise_time_min);}
		if (temp == SunAlarm.REFERENCE_SUNSET) {txttmp = (String) mesRessources.getText(R.string.sunset_time_min);}
		myResult+= txttmp;
    	return myResult;
    }
    
    protected int getAlarmIcon(SunAlarm sa) {
     	return (sa.isActive())?ICON_main_alarm_active:ICON_main_alarm_inactive;
    }

    
    /* **************************************************************
     * Functions to MANAGE PREFERENCES (RESET, LOAD and SAVE)
     **************************************************************** */

    public void resetPreferences(){
    	int mode = Activity.MODE_PRIVATE;
    	SharedPreferences mySharedPreferences = getSharedPreferences(MYPREFS,mode);
    	SharedPreferences.Editor editor = mySharedPreferences.edit();
    	editor.clear();
    	editor.commit();
    	toastShortInfo("/!\\ Preferences cleared /!\\");
    }
    
    public void saveToneSetup() {
    	try {
	    	/* Preparation of the save preferences informations */
	    	int mode = Activity.MODE_PRIVATE;	    		    	
	    	SharedPreferences mySharedPreferences = getSharedPreferences(applicationStartup.MYPREFS,mode);
	    	SharedPreferences.Editor editor = mySharedPreferences.edit();
	    	editor.putInt("general_volume_level", selectedVolumeLevel);
	    	editor.putInt("general_tone", selectedTone);
	    	editor.commit();
    	} catch (Exception e) {
    		toastLongInfo("Error saving volume level (" + e.getMessage() + ")");
    	}
    }

    public void loadToneSetup() {
    	try {
        	int mode = Activity.MODE_PRIVATE;  
        	SharedPreferences mySharedPreferences = theContext.getSharedPreferences(applicationStartup.MYPREFS,mode);
        	selectedVolumeLevel = mySharedPreferences.getInt("general_volume_level", MENU_VOLUME_MEDIUM);
        	selectedTone        = mySharedPreferences.getInt("general_tone", MENU_TONE_POP);
    	} catch (Exception e) {
    		ErrorReporter.getInstance().handleException(e);
    	}
    }

    public static void savePreferences(Context theContext){
    	try {
	    	/* Preparation of the save preferences informations */
	    	int mode = Activity.MODE_PRIVATE;
	    		    	
	    	SharedPreferences mySharedPreferences = theContext.getSharedPreferences(applicationStartup.MYPREFS,mode);
	    	SharedPreferences.Editor editor = mySharedPreferences.edit();
	
	    	editor.putBoolean("positionSet", applicationStartup.applicationPOSITIONset);
	    	
	    	//GENERAL PREFERENCES
	    	editor.putBoolean("morningVStwilight", applicationStartup.sunriseVStwilight);
	    	editor.putBoolean("eveningVStwilight", applicationStartup.sunsetVStwilight);

	    	editor.putBoolean("application_already_loaded", true);
	    	editor.putBoolean("positionSet", applicationStartup.applicationPOSITIONset);
	    	
	    	//POSITION
	    	editor.putFloat("latitude", (float) applicationStartup.currentPosition.getLatitude());
	    	editor.putFloat("longitude", (float) applicationStartup.currentPosition.getLongitude());
	    	
	    	//ALARM1
	    	editor.putInt("alarm1_referenceHours", applicationStartup.sAlarm1.getReferenceTime().getHours());
	    	editor.putInt("alarm1_referenceMinutes", applicationStartup.sAlarm1.getReferenceTime().getMinutes());
	    	editor.putBoolean("alarm1_relativeToEvent", applicationStartup.sAlarm1.isBeforeReference());
	    	editor.putInt("alarm1_event", applicationStartup.sAlarm1.getMomentReference());
	    	editor.putInt("alarm1_hours", applicationStartup.sAlarm1.getAlarmHour());
	    	editor.putInt("alarm1_minutes", applicationStartup.sAlarm1.getAlarmMinute());
	    	editor.putBoolean("alarm1_activeStatus", applicationStartup.sAlarm1.isActive());
	    	editor.putString("alarm1ID", applicationStartup.sAlarm1.getID());
	    	editor.putString("alarm1_NOTIFY", sAlarm1.getAlarmTimeString());
	    	
	      	//ALARM2
	    	editor.putInt("alarm2_referenceHours", applicationStartup.sAlarm2.getReferenceTime().getHours());
	    	editor.putInt("alarm2_referenceMinutes", applicationStartup.sAlarm2.getReferenceTime().getMinutes());
	    	editor.putBoolean("alarm2_relativeToEvent", applicationStartup.sAlarm2.isBeforeReference());
	    	editor.putInt("alarm2_event", applicationStartup.sAlarm2.getMomentReference());
	    	editor.putInt("alarm2_hours", applicationStartup.sAlarm2.getAlarmHour());
	    	editor.putInt("alarm2_minutes", applicationStartup.sAlarm2.getAlarmMinute());
	    	editor.putBoolean("alarm2_activeStatus", applicationStartup.sAlarm2.isActive());
	    	editor.putString("alarm2ID", applicationStartup.sAlarm2.getID());
	    	editor.putString("alarm2_NOTIFY", sAlarm2.getAlarmTimeString());
	    	
	    	//For the BROADCASTER
	    	editor.putString("alarm1_AlarmTime", applicationStartup.sAlarm1.getAlarmTimeString());
	    	editor.putString("alarm2_AlarmTime", applicationStartup.sAlarm2.getAlarmTimeString());
	    	
	    	editor.commit();

    	} catch (Exception e) {
    		Resources mesRessources = theContext.getResources();
    		String message = mesRessources.getText(R.string.system_error) + e.getMessage();
    		toastInfo(theContext, message);
    	}
    }    

    public static void loadApplicationLocation(Context theContext) {
    	int mode = Activity.MODE_PRIVATE;  
    	SharedPreferences mySharedPreferences = theContext.getSharedPreferences(applicationStartup.MYPREFS,mode);
    	applicationStartup.currentPosition.setLatitude(mySharedPreferences.getFloat("latitude", 48.846923f));
    	applicationStartup.currentPosition.setLongitude(mySharedPreferences.getFloat("longitude", 2.337196f));
    	applicationStartup.applicationPOSITIONset = mySharedPreferences.getBoolean("positionSet", false);
    }
    
    public static void loadPreferences(Context theContext) {
    	int mode = Activity.MODE_PRIVATE;  
    	SharedPreferences mySharedPreferences = theContext.getSharedPreferences(applicationStartup.MYPREFS,mode);
    	applicationStartup.applicationAlreadyLoaded = mySharedPreferences.getBoolean("application_already_loaded", false);
    	applicationStartup.applicationPOSITIONset = mySharedPreferences.getBoolean("positionSet", false);

    	//ALARM1
    	Time timeReference = new Time(0,0,0.0d);    	
    	timeReference.setHours(mySharedPreferences.getInt("alarm1_referenceHours", referenceHours[SunAlarm.REFERENCE_SUNRISE].getHours()));
    	timeReference.setMinutes(mySharedPreferences.getInt("alarm1_referenceMinutes", referenceHours[SunAlarm.REFERENCE_SUNRISE].getMinutes()));
    	applicationStartup.sAlarm1.setTimeReference(timeReference);
    	if(mySharedPreferences.getBoolean("alarm1_relativeToEvent",true)) { applicationStartup.sAlarm1.setIsBefore(); } else { applicationStartup.sAlarm1.setIsAfter(); }
    	applicationStartup.sAlarm1.setMomentReference(mySharedPreferences.getInt("alarm1_event", SunAlarm.REFERENCE_SUNRISE));
    	applicationStartup.sAlarm1.setAlarmHour(mySharedPreferences.getInt("alarm1_hours", 0));
    	applicationStartup.sAlarm1.setAlarmMinutes(mySharedPreferences.getInt("alarm1_minutes", 45));
    	if(mySharedPreferences.getBoolean("alarm1_activeStatus", false)) { applicationStartup.sAlarm1.activate(); } else { applicationStartup.sAlarm1.desactivate(); }
    	applicationStartup.sAlarm1.setID(mySharedPreferences.getString("alarm1ID", sAlarm1.getID()));
    	sAlarm1.setTimeReference(referenceHours[sAlarm1.getMomentReference()]);
    	applicationStartup.sAlarm1.updateAlarmTime();

    	//ALARM2
    	Time time2Reference = new Time(0,0,0.0d);    	
    	time2Reference.setHours(mySharedPreferences.getInt("alarm2_referenceHours", referenceHours[SunAlarm.REFERENCE_SUNRISE].getHours()));
    	time2Reference.setMinutes(mySharedPreferences.getInt("alarm2_referenceMinutes", referenceHours[SunAlarm.REFERENCE_SUNRISE].getMinutes()));
    	applicationStartup.sAlarm2.setTimeReference(time2Reference);
    	if(mySharedPreferences.getBoolean("alarm2_relativeToEvent",true)) { applicationStartup.sAlarm2.setIsBefore(); } else { applicationStartup.sAlarm2.setIsAfter(); }
    	applicationStartup.sAlarm2.setMomentReference(mySharedPreferences.getInt("alarm2_event", SunAlarm.REFERENCE_SUNSET));
    	applicationStartup.sAlarm2.setAlarmHour(mySharedPreferences.getInt("alarm2_hours", 0));
    	applicationStartup.sAlarm2.setAlarmMinutes(mySharedPreferences.getInt("alarm2_minutes", 35));
    	if(mySharedPreferences.getBoolean("alarm2_activeStatus", false)) { applicationStartup.sAlarm2.activate(); } else { applicationStartup.sAlarm2.desactivate(); }
    	applicationStartup.sAlarm2.setID(mySharedPreferences.getString("alarm2ID", sAlarm2.getID()));
    	sAlarm2.setTimeReference(referenceHours[sAlarm2.getMomentReference()]);
    	applicationStartup.sAlarm2.updateAlarmTime();

    	//MORNING display (sunrise or morning twilight)
    	applicationStartup.sunriseVStwilight = mySharedPreferences.getBoolean("morningVStwilight", true);
    	
    	//EVENING display (sunset or evening twilight)
    	applicationStartup.sunsetVStwilight = mySharedPreferences.getBoolean("eveningVStwilight", true);
    	
    }
    
   
    /* **************************************************************
     * Functions to launch other ACTIVITIES
     **************************************************************** */
    
    public void launchAlarmSetActivity(int sa){
    	Intent intent = new Intent();
		intent.setClass(applicationStartup.this, alarmSetActivity.class);
		Bundle bundle = new Bundle();
		bundle.putInt("alarmToConsider", sa);
		intent.putExtras(bundle);
		startActivityForResult(intent, SUB_ACTIVITY_REQUEST_CODE);
    }

    public void launchCoordinatesActivity() {
    	Intent intent = new Intent();
		intent.setClass(applicationStartup.this, coordinatesActivity.class);
		startActivityForResult(intent, SUB_ACTIVITY_REQUEST_CODE);		
    }

    
    /* **************************************************************
     * Actions link to the MAIN ACTIVITY
     **************************************************************** */
    public void doActionsOnClick(View parentId, int actionToPerform){
    	
		Resources mesRessources = this.getResources();
        TextView aTitle = (TextView) parentId.findViewById(R.id.title);
        TextView aText = (TextView) parentId.findViewById(R.id.value);
        ImageView anIcon = (ImageView) parentId.findViewById(R.id.icon);
        		
		if (actionToPerform== applicationStartup.MAIN_CHOICE_COORDINATES  ) {
			launchCoordinatesActivity();
			updateReferenceHours();
			loadApplicationLocation(this);
		}

		if (actionToPerform == applicationStartup.MAIN_CHOICE_MORNING_TIME) {
			if (!sunriseVStwilight){
				aTitle.setText(mesRessources.getText(R.string.sunrise_time));
				aText.setText(referenceHours[SunAlarm.REFERENCE_SUNRISE].toSimplifiedString());
				sunriseVStwilight = !sunriseVStwilight;
			} else {
				aTitle.setText(mesRessources.getText(R.string.morning_twilight_time));
				aText.setText(referenceHours[SunAlarm.REFERENCE_MORNING_TWILIGHT].toSimplifiedString());
				sunriseVStwilight = !sunriseVStwilight;
			}			
		}

		if (actionToPerform == applicationStartup.MAIN_CHOICE_EVENING_TIME) {
			if (!sunsetVStwilight) {
				aTitle.setText(mesRessources.getText(R.string.sunset_time));
				aText.setText(referenceHours[SunAlarm.REFERENCE_SUNSET].toSimplifiedString());
				sunsetVStwilight = !sunsetVStwilight;
			} else {
				aTitle.setText(mesRessources.getText(R.string.evening_twilight_time));
				aText.setText(referenceHours[SunAlarm.REFERENCE_EVENING_TWILIGHT].toSimplifiedString());
				sunsetVStwilight = !sunsetVStwilight;
			}
		}

		if (actionToPerform == applicationStartup.MAIN_CHOICE_ALARM_1) { //Alarm 1
			launchAlarmSetActivity(1);		
		}

		if (actionToPerform == applicationStartup.MAIN_CHOICE_ALARM_2) { //Alarm 2
			launchAlarmSetActivity(2);
		}
		
		if (actionToPerform == applicationStartup.MAIN_CHOICE_NOTIFICATION) {
  		  	Intent selectToneIntent = new Intent(this,SelectToneActivity.class);
		  	startActivity(selectToneIntent);	
		}
		
		savePreferences(this);
		saveToneSetup();
	}

	public void doActionsOnLongClick(View parentId, int actionToPerform){

        TextView aTitle = (TextView) parentId.findViewById(R.id.title);
        TextView aText = (TextView) parentId.findViewById(R.id.value);
        ImageView anIcon = (ImageView) parentId.findViewById(R.id.icon);
		
		if (actionToPerform== applicationStartup.MAIN_CHOICE_COORDINATES  ) {
			try { 
		     final Intent myIntent = new Intent(android.content.Intent.ACTION_VIEW, Uri.parse("geo:" + currentPosition.getLatitude() + "," + currentPosition.getLongitude() + "?z=" + MAPS_ZOOM_LEVEL )); 
		     toastLongInfo((String)getText(R.string.openGoogleMaps));
		     startActivity(myIntent); 
			} catch (Exception e) { 
			}
		}
		
		if (actionToPerform == applicationStartup.MAIN_CHOICE_MORNING_TIME) {

		}
		
		if (actionToPerform == applicationStartup.MAIN_CHOICE_EVENING_TIME) {
			
		}
		
		if (actionToPerform == applicationStartup.MAIN_CHOICE_ALARM_1) {
			if (!applicationStartup.applicationPOSITIONset) {
				toastLongInfo(""+getText(R.string.app_no_coordinates_toggle_alarm));
			} else {
				sAlarm1.toggleActivate();
				scheduleAlarm();
				setNotification();
				aTitle.setText(buildAlarmTitle(sAlarm1));
				aText.setText(buildAlarmContent(sAlarm1));
				anIcon.setImageResource(getAlarmIcon(sAlarm1));
			}
		}
		
		if (actionToPerform == applicationStartup.MAIN_CHOICE_ALARM_2) {
			if (!applicationStartup.applicationPOSITIONset) {
				toastLongInfo(""+getText(R.string.app_no_coordinates_toggle_alarm));
			} else {
				sAlarm2.toggleActivate();
				scheduleAlarm();
				setNotification();
				aTitle.setText(buildAlarmTitle(sAlarm2));
				aText.setText(buildAlarmContent(sAlarm2));
				anIcon.setImageResource(getAlarmIcon(sAlarm2));
			}
		}
		
		savePreferences(this);
		saveToneSetup();
	}


	public void playSoundFile(String pathToMP3File) {
	 
	  backupVolumeSettings();

	  float theVolume = 0.5f;
	  MediaPlayer mp;
	  AudioManager am;
	  
	  //Retrieve volume level
  	  switch (selectedVolumeLevel) {
  	  	case MENU_VOLUME_SILENCE: theVolume = alarmReceiverDisplay.MUSIC_VOLUME_SILENCE_LEVEL;break;
  	  	case MENU_VOLUME_LOW: theVolume = alarmReceiverDisplay.MUSIC_VOLUME_LOW_LEVEL;break;
  	  	case MENU_VOLUME_MEDIUM: theVolume = alarmReceiverDisplay.MUSIC_VOLUME_MEDIUM_LEVEL;break;
  	  	case MENU_VOLUME_HIGH: theVolume = alarmReceiverDisplay.MUSIC_VOLUME_HIGH_LEVEL;break;
  	  }	
  	  
		//- PLAY SOUND --------------------------------------------------------------------------------
		try {
			mp = new MediaPlayer(); 
		    mp.setDataSource("/sdcard/test_cbr.mp3");
		    //mp.setDataSource(pathToMP3File);
	        mp.setScreenOnWhilePlaying(true);
	        mp.setAudioStreamType(alarmReceiverDisplay.STREAM_TO_USE);
	        am = (AudioManager) theContext.getSystemService(Context.AUDIO_SERVICE);	
	        am.setStreamVolume(alarmReceiverDisplay.STREAM_TO_USE, am.getStreamMaxVolume(alarmReceiverDisplay.STREAM_TO_USE), 0);
	        mp.setVolume(alarmReceiverDisplay.MUSIC_VOLUME_MEDIUM_LEVEL, alarmReceiverDisplay.MUSIC_VOLUME_MEDIUM_LEVEL);
    		mp.setVolume(theVolume, theVolume);
	        mp.start();
	        mp.setOnCompletionListener(new OnCompletionListener() {
				@Override
				public void onCompletion(MediaPlayer mp) {restoreVolumeSettings();}
			});
		
		} catch (Exception e) {
			Toast.makeText(this, "Music exception: " + e.getMessage(),Toast.LENGTH_SHORT).show();
		}
	}
	
	
	public void playSoundNotification() {
		backupVolumeSettings();
		
	  float theVolume = 0.5f;
	  MediaPlayer mp;
	  AudioManager am;
	  
	  //Retrieve volume level
  	  switch (selectedVolumeLevel) {
  	  	case MENU_VOLUME_SILENCE:
  	  		theVolume = alarmReceiverDisplay.MUSIC_VOLUME_SILENCE_LEVEL;
  	  		break;
  	  	case MENU_VOLUME_LOW:
  	  		theVolume = alarmReceiverDisplay.MUSIC_VOLUME_LOW_LEVEL;
  	  		break;
  	  	case MENU_VOLUME_MEDIUM:
  	  		theVolume = alarmReceiverDisplay.MUSIC_VOLUME_MEDIUM_LEVEL;
  	  		break;
  	  	case MENU_VOLUME_HIGH:
  	  	theVolume = alarmReceiverDisplay.MUSIC_VOLUME_HIGH_LEVEL;
  	  	break;
  	  }	
  	  
		//- PLAY SOUND --------------------------------------------------------------------------------
		try {
			mp = new MediaPlayer(); 
			mp = MediaPlayer.create(theContext, selectedTone);
	        mp.setScreenOnWhilePlaying(true);
	        mp.setAudioStreamType(alarmReceiverDisplay.STREAM_TO_USE);

	        am = (AudioManager) theContext.getSystemService(Context.AUDIO_SERVICE);	
	        am.setStreamVolume(alarmReceiverDisplay.STREAM_TO_USE, am.getStreamMaxVolume(alarmReceiverDisplay.STREAM_TO_USE), 0);
	        
	        mp.setVolume(alarmReceiverDisplay.MUSIC_VOLUME_MEDIUM_LEVEL, alarmReceiverDisplay.MUSIC_VOLUME_MEDIUM_LEVEL);
    		mp.setVolume(theVolume, theVolume);
	        mp.start();
	        mp.setOnCompletionListener(new OnCompletionListener() {
				@Override
				public void onCompletion(MediaPlayer mp) {
					restoreVolumeSettings();
				}
			});
		
		} catch (Exception e) {
			Toast.makeText(this, "Music exception: " + e.getMessage(),Toast.LENGTH_SHORT).show();
		}
		
				
	}

    
    /* **************************************************************
     * GUI fonctions
     **************************************************************** */

	public void displayMainView(){
    	Resources mesRessources = this.getResources();

    	ArrayList<HashMap<String, Object>> mylist = new ArrayList<HashMap<String, Object>>();
        String disText = new String(), disValue = new String();
        
        // COORDINATES item
        HashMap<String, Object> map = new HashMap<String, Object>();
        map.put("title", mesRessources.getText(R.string.coordinates));
        if (!applicationStartup.applicationPOSITIONset) {
        	map.put("value", getString(R.string.app_no_coordinates_in_main_page));
        } else {
        	map.put("value", currentPosition.toSimplifyString());
        }
        map.put("icone", ICON_main_coordinates);
        mylist.add(map);

        // SUNRISE TIME item
        //Determine the text
        if (sunriseVStwilight) {
        	disText = (String) mesRessources.getText(R.string.sunrise_time);
       		disValue = referenceHours[SunAlarm.REFERENCE_SUNRISE].toSimplifiedString();

        } else {
        	disText = (String) mesRessources.getText(R.string.morning_twilight_time);
       		disValue = referenceHours[SunAlarm.REFERENCE_MORNING_TWILIGHT].toSimplifiedString();
        }
        map = new HashMap<String, Object>();
        map.put("title", disText);
        map.put("value", disValue);
        map.put("icone", ICON_main_sunrise);
        mylist.add(map);

        // SUNSET TIME item
        //Determine the text
		if (sunsetVStwilight) {
        	disText = (String) mesRessources.getText(R.string.sunset_time);
        	disValue = referenceHours[SunAlarm.REFERENCE_SUNSET].toSimplifiedString();
        } else {
        	disText = (String) mesRessources.getText(R.string.evening_twilight_time);
        	disValue = referenceHours[SunAlarm.REFERENCE_EVENING_TWILIGHT].toSimplifiedString();        	
        }
		
		map = new HashMap<String, Object>();
        map.put("title", disText);
        map.put("value", disValue);
        map.put("icone",ICON_main_sunset);
        mylist.add(map);
        
        // FIRST ALARM item
        map = new HashMap<String, Object>();
        map.put("title", buildAlarmTitle(sAlarm1));
        map.put("value", buildAlarmContent(sAlarm1));
        map.put("icone", getAlarmIcon(sAlarm1));
        mylist.add(map);
        
        // SECOND ALARM item
        map = new HashMap<String, Object>();
        map.put("title", buildAlarmTitle(sAlarm2));
        map.put("value", buildAlarmContent(sAlarm2));
        map.put("icone", getAlarmIcon(sAlarm2));
        mylist.add(map);

        // SOUND Setup
        map = new HashMap<String, Object>();
        map.put("title", (String)getText(R.string.MENU_TONE_SETTINGS));
        map.put("value", (String)getText(R.string.MENU_TONE_SETTINGS_SUB));
        map.put("icone", R.drawable.sound);
        mylist.add(map);

        
      setContentView(R.layout.main_activity);

      //Defining the FONT to the title TextView
      Typeface face=Typeface.createFromAsset(getAssets(), applicationStartup.GLOBAL_FONT_TO_USE);
      TextView tv=(TextView)findViewById(R.id.maintitle);
      tv.setTypeface(face);
      
      tv.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				displayApplicationInformation();
			}
		});
      
      
      ImageView iv=(ImageView)findViewById(R.id.imglogo);      
      iv.setOnLongClickListener(new OnLongClickListener() {
    		@Override
    		public boolean onLongClick(View v) {
    			warpZoneActivation();
    			return false;
    		}
    		});

      
      ListView myItems = (ListView) findViewById(android.R.id.list);        
      
      // ADAPTER Creation        
      SimpleAdapter monAdapter = new SimpleAdapter(this, mylist, 
      			R.layout.item,
      			new String[] {"title", "value","icone"}, new int[] {R.id.title, R.id.value, R.id.icon});
      
      // Add items thanks to the adapter
      myItems.setAdapter(monAdapter);      
      myItems.setClickable(true);        

      // Add the LISTENER, with redirection to the doActions method
      myItems.setOnItemClickListener(new OnItemClickListener() {
      	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,long arg3) {        		
              doActionsOnClick(arg1,arg2);
      	}
		});

      myItems.setOnItemLongClickListener(
    		  new OnItemLongClickListener() {
				public boolean onItemLongClick(AdapterView<?> arg0, View arg1,int arg2, long arg3) {
					doActionsOnLongClick(arg1,arg2);
					return true;
				}
    			  
			}
      );
            
	}
	
	public void displayApplicationInformation() {
	    new AlertDialog.Builder(this)
	      .setTitle(getText(R.string.app_name) + " v." + getText(R.string.app_version))
	      .setPositiveButton(getText(R.string.okcancel_OK), null)
	      .setMessage((String)getText(R.string.app_compilationdate) + getText(R.string.appp_info))
	      .setIcon(android.R.drawable.ic_dialog_info)
	      .setNeutralButton((String)getText(R.string.websitetitle), new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
	    		  	Intent i = new Intent(Intent.ACTION_VIEW);
	    		  	i.setData(Uri.parse(applicationURL));
	    		  	startActivity(i);
				}
		})
	      .show();
	}

	public void displaySetCoordsMessage() {
	    new AlertDialog.Builder(this)
	      .setTitle(R.string.app_no_coordinates_title)
	      .setPositiveButton(getText(R.string.yesno_YES), new DialogInterface.OnClickListener (){
			@Override
			public void onClick(DialogInterface arg0, int arg1) {
				launchCoordinatesActivity();
			}
			} )
	      .setNegativeButton(getText(R.string.yesno_NO), null)
	      .setMessage(getText(R.string.app_no_coordinates_text))
	      .show();

	}
	
	public void displayMainHelp() {
		
	    new AlertDialog.Builder(this)
	      .setTitle(getText(R.string.app_name) + " v." + getText(R.string.app_version))
	      .setPositiveButton(getText(R.string.okcancel_OK), null)
	      .setMessage("" + getText(R.string.help_main))
	      .show();
	}	
	
	public void displayWelcomeMessage() {
	    new AlertDialog.Builder(this)
	      .setTitle(getText(R.string.app_name) + " v." + getText(R.string.app_version))
	      .setPositiveButton(getText(R.string.okcancel_OK), null)
	      .setMessage("" + getText(R.string.app_welcome_text))
	      .setIcon(android.R.drawable.ic_dialog_info)
	      .show();
	}
	
	public void displayNewsInformation() {
		try {
	    	int mode = Activity.MODE_PRIVATE;  
	    	SharedPreferences mySharedPreferences = theContext.getSharedPreferences(applicationStartup.MYPREFS,mode);
	    	
	    	if (mySharedPreferences.getBoolean("display_new_version_information_"+getText(R.string.app_version), true)) {
				//Display information
			    new AlertDialog.Builder(this)
			      .setTitle("" + getText(R.string.news_on) + " v." + getText(R.string.app_version))
			      .setPositiveButton(getText(R.string.okcancel_OK), null)
			      .setMessage("" + getText(R.string.news_for_this_version))
			      .setIcon(android.R.drawable.ic_dialog_info)
			      .show();
			    		    	
		    	SharedPreferences.Editor editor = mySharedPreferences.edit();
		    	editor.putBoolean("display_new_version_information_"+getText(R.string.app_version), false);
		    	editor.commit();
		
		    	//GENERAL PREFERENCES
		    	editor.putBoolean("morningVStwilight", applicationStartup.sunriseVStwilight);

	    	} else {
	    		// null
	    	}
		} catch (Exception e) {
			// null
		}
	}

	
	private void setNotification () {
		mNotificationManager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
		mNotificationManager.cancel(MY_APP_NOTIFICATION_ID);
		
		if (sAlarm1.isActive() || sAlarm2.isActive()) {
	
			CharSequence from = getText(R.string.app_name);
			
			String message = "";
			if (sAlarm1.isActive() && sAlarm2.isActive()) {
				message += getText(R.string.t_alarms);
				message += " " + getText(R.string.activateds);
				message += " - " + sAlarm1.getAlarmTimeString() + " " + getText(R.string.and) + " " + sAlarm2.getAlarmTimeString();
			} else {
				message += getText(R.string.t_alarm); 
				message += " " +getText(R.string.activated);
				if (sAlarm1.isActive()) message += " - " + sAlarm1.getAlarmTimeString(); else message += " - " + sAlarm2.getAlarmTimeString();
			}
			
	        //message = getText(R.string.t_alarm) + " " + getText(R.string.activated);
	        PendingIntent contentIntent = PendingIntent.getActivity(this, 0, new Intent(this, applicationStartup.class), 0);
	        String tickerText = (String) message;
	        Notification notif = new Notification(R.drawable.icon_sun, tickerText, System.currentTimeMillis());
	        notif.flags |= Notification.FLAG_NO_CLEAR;
	        notif.setLatestEventInfo(this, from, message, contentIntent);
	        mNotificationManager.notify(MY_APP_NOTIFICATION_ID, notif);
		}
	}


	/* **************************************************************
     * General utility functions
     **************************************************************** */
	public void warpZoneActivation() {
		warpZoneCounter++;
		if (warpZoneCounter>=WARP_ZONE_LIMIT){
			warpZoneCounter=0;
			resetPreferences();
		}
	}
	
	public void updateReferenceHours() {
		try {
			referenceHours[SunAlarm.REFERENCE_MORNING_TWILIGHT] = Sun.morningCivilTwilightTime(julianCalendar, currentPosition, currentTimeZone, daylightSavingTime);
			referenceHours[SunAlarm.REFERENCE_SUNRISE] = Sun.sunriseTime(julianCalendar, currentPosition, currentTimeZone, daylightSavingTime);
			referenceHours[SunAlarm.REFERENCE_SUNSET] = Sun.sunsetTime(julianCalendar, currentPosition, currentTimeZone, daylightSavingTime);
			referenceHours[SunAlarm.REFERENCE_EVENING_TWILIGHT] = Sun.eveningCivilTwilightTime(julianCalendar, currentPosition, currentTimeZone, daylightSavingTime);
		} catch (IllegalArgumentException e) {
			crashDebugAdditionalInformation();
			ErrorReporter.getInstance().handleSilentException(e);
			referenceHours[SunAlarm.REFERENCE_MORNING_TWILIGHT] = new Time(5,26,0.0d);
			referenceHours[SunAlarm.REFERENCE_SUNRISE] = new Time(6,05,0.0d);
			referenceHours[SunAlarm.REFERENCE_SUNSET] = new Time(21,28,0.0d);
			referenceHours[SunAlarm.REFERENCE_EVENING_TWILIGHT] = new Time(22,7,0.0d);
		}
	}
	
	/* **************************************************************
     * Alarm Activation functions
     **************************************************************** */
	private void cancelAlarm(int alarmIDToConsider) {
		AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
		Intent intent = new Intent(this, alarmReceiver.class);
		PendingIntent pendingintent = PendingIntent.getBroadcast(this, alarmIDToConsider, intent, 0);
		am.cancel(pendingintent);		
	}
	
	private void onSameTimeSchedule() {
		toastLongInfo((String)getText(R.string.warning_same_hour));
	}

	
	private void scheduleAlarm() {
		//Change double SAME time schedule
		if (
				(sAlarm1.isActive() && sAlarm2.isActive())
				&&
				(sAlarm1.getAlarmTimeString().compareTo(sAlarm2.getAlarmTimeString()) == 0 )
		) {
			if (doubleAlarmWarningAlreadyShown) {
				//
			} else {
				onSameTimeSchedule();
				doubleAlarmWarningAlreadyShown = true;
			}
			
		} else {
			doubleAlarmWarningAlreadyShown = false;
		}
		
		//We start by cancelling both alarms
		cancelAlarm(ALARM_ID_1);
		cancelAlarm(ALARM_ID_2);
		
		//Get an instance of the Alarm Manager Service
		AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
		Intent intent = new Intent(this, alarmReceiver.class);
		
		PendingIntent pendingintent1 = PendingIntent.getBroadcast(this, ALARM_ID_1, intent, 0);
		PendingIntent pendingintent2 = PendingIntent.getBroadcast(this, ALARM_ID_2, intent, 0);
		
		Calendar reveil  = Calendar.getInstance();
		Calendar cal = Calendar.getInstance();
		long diff;
		
		String textInfo = "";
		
		if(sAlarm1.isActive()){
			reveil  = Calendar.getInstance();
			cal = Calendar.getInstance();
			
			if (!debugMode) reveil.set(Calendar.HOUR_OF_DAY, sAlarm1.getAlarmTime().getHours());
			if (debugMode)  reveil.set(Calendar.HOUR_OF_DAY,cal.get(Calendar.HOUR_OF_DAY));
			if (!debugMode) reveil.set(Calendar.MINUTE, sAlarm1.getAlarmTime().getMinutes());
			if (debugMode)  reveil.set(Calendar.MINUTE,cal.get(Calendar.MINUTE)+1);
			if(reveil.compareTo(Calendar.getInstance()) == -1)
			reveil.add(Calendar.DAY_OF_YEAR, 1);
			reveil.set(Calendar.SECOND, 0);
			cal.set(Calendar.SECOND, 0);
			diff = reveil.getTimeInMillis() - cal.getTimeInMillis();
			am.set(AlarmManager.RTC_WAKEUP,cal.getTimeInMillis() + diff, pendingintent1);

			textInfo = ""+ getText(R.string.SCHED_alarm1);
			if (cal.get(Calendar.DAY_OF_MONTH) == reveil.get(Calendar.DAY_OF_MONTH)) textInfo += " " + getText(R.string.SCHED_today);
			if ((cal.get(Calendar.DAY_OF_MONTH)+1) == reveil.get(Calendar.DAY_OF_MONTH)) textInfo += " " + getText(R.string.SCHED_tomorrow);
			textInfo += " " + getText(R.string.at) + " " + reveil.get(Calendar.HOUR_OF_DAY) + ":" + ((reveil.get(Calendar.MINUTE))<10?"0"+reveil.get(Calendar.MINUTE):reveil.get(Calendar.MINUTE));
		}

		if(sAlarm2.isActive()){
			reveil  = Calendar.getInstance();
			cal = Calendar.getInstance();
			if (!debugMode) reveil.set(Calendar.HOUR_OF_DAY, sAlarm2.getAlarmTime().getHours());
			if (debugMode)  reveil.set(Calendar.HOUR_OF_DAY,cal.get(Calendar.HOUR_OF_DAY));
			if (!debugMode) reveil.set(Calendar.MINUTE, sAlarm2.getAlarmTime().getMinutes());
			if (debugMode)  reveil.set(Calendar.MINUTE,cal.get(Calendar.MINUTE)+1);
			if(reveil.compareTo(Calendar.getInstance()) == -1)
			reveil.add(Calendar.DAY_OF_YEAR, 1);
			reveil.set(Calendar.SECOND, 0);
			cal.set(Calendar.SECOND, 0);
			diff = reveil.getTimeInMillis() - cal.getTimeInMillis();
			am.set(AlarmManager.RTC_WAKEUP,cal.getTimeInMillis() + diff, pendingintent2);

			if (textInfo!="") textInfo+="\n\n";
			textInfo += ""+ getText(R.string.SCHED_alarm2);
			if (cal.get(Calendar.DAY_OF_MONTH) == reveil.get(Calendar.DAY_OF_MONTH)) textInfo += " " + getText(R.string.SCHED_today);
			if ((cal.get(Calendar.DAY_OF_MONTH)+1) == reveil.get(Calendar.DAY_OF_MONTH)) textInfo += " " + getText(R.string.SCHED_tomorrow);
			textInfo += " " + getText(R.string.at) +" "+ reveil.get(Calendar.HOUR_OF_DAY) + ":" + ((reveil.get(Calendar.MINUTE))<10?"0"+reveil.get(Calendar.MINUTE):reveil.get(Calendar.MINUTE));
		}
		
		if (debugMode && textInfo!="") toastLongInfo(textInfo);			

	}

	
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode == 0 && requestCode == SUB_ACTIVITY_REQUEST_CODE) {
	        loadApplicationLocation(this);
	        loadToneSetup();
	        updateReferenceHours();
	        loadPreferences(this);
	        displayMainView();
	        savePreferences(this) ;
	        saveToneSetup();
	        
	        scheduleAlarm();
	        setNotification();
	    }
	}

    public boolean onCreateOptionsMenu(Menu menu) {
        //ADD QUICK HELP
        menu.add(0,MENU_QUICK_HELP,0,(String)getText(R.string.MENU_quick_help))
        	.setIcon(android.R.drawable.ic_menu_help);
        
        //ADD ABOUT
        menu.add(0, MENU_ABOUT_ID, 0, (String)getText(R.string.MENU_about) ).setIcon(android.R.drawable.ic_menu_info_details);

        return true;
    }

    public boolean onOptionsItemSelected (MenuItem item){
    	  switch (item.getItemId()) {
    	  case MENU_QUICK_HELP:
    		  displayMainHelp();
    		  return true;
    	  case MENU_ABOUT_ID:
    	    displayApplicationInformation();
    	    return true;
      	}    	  
    	return false;
    }

    
	public void onWindowFocusChanged (boolean hasFocus) {
    	if (hasFocus)  {
    		loadPreferences(this);
    		loadToneSetup();
    		updateReferenceHours();
    		savePreferences(this);
    	} else {
    		//Nothing...
    	}
	}
	
	public boolean onKeyDown(int keyCode, KeyEvent event){ 
		if(keyCode==KeyEvent.KEYCODE_BACK) {
			finish();
			return true; 
		} 

		if(keyCode==KeyEvent.KEYCODE_HOME) {
			finish();
			return true; 
		} 

		return super.onKeyDown(keyCode, event); 
	}

	boolean backupVolumeSettings() {
		boolean done = false;
		AudioManager am;
		try {
			am = (AudioManager) theContext.getSystemService(Context.AUDIO_SERVICE);
			initialStreamVolume = am.getStreamVolume(AudioManager.STREAM_MUSIC);
			initialSystemStreamVolume = am.getStreamVolume(AudioManager.STREAM_SYSTEM);
			done = true;
		} catch (Exception e) {
			toastLongInfo("Initialisation error (" + e.getMessage() + ")");
		}
		return done;
	}
	
	private boolean restoreVolumeSettings() {
		boolean done = false;
		AudioManager am;
		try {
			am = (AudioManager) theContext.getSystemService(Context.AUDIO_SERVICE);
			am.setStreamVolume(AudioManager.STREAM_MUSIC, initialStreamVolume, 0);
			am.setStreamVolume(AudioManager.STREAM_SYSTEM, initialSystemStreamVolume, 0);
			done = true;
		} catch (Exception e) {
			toastLongInfo("Restore error (" + e.getMessage() + ")");
		}
		return done;
	}

	

	
	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        
    	super.onCreate(savedInstanceState);
    	
        theContext = this;
        if (debugMode) resetPreferences();
        crashDebugAdditionalInformation();
        
        loadApplicationLocation(this);
        loadToneSetup();
        updateReferenceHours();
        loadPreferences(this);
        displayMainView();
        scheduleAlarm();
        setNotification();
        crashDebugAdditionalInformation();
      	
        //setContentView(null);
        
        savePreferences(this) ;
        saveToneSetup();

        if (!applicationStartup.applicationPOSITIONset || debugMode) {
        	displaySetCoordsMessage();
        }

        
        // To display the "News on this version" popup message
        displayNewsInformation();

        //In case of first load, POPUP !
        if (!applicationAlreadyLoaded || debugMode) {
        	displayWelcomeMessage();
        }
        
   }
	
}